<template>
  <view class="bg-[#f5f7fa] min-h-screen p-[30rpx]">
    <view class="max-w-[600rpx] mx-auto">
      <!-- 头部 -->
      <view class="text-center mb-[40rpx]">
        <view class="w-[80rpx] h-[80rpx] bg-gradient-to-br from-[#07C160] to-[#00D4AA] rounded-[20rpx] flex items-center justify-center mx-auto mb-[20rpx]">
          <IconFont name="icon-wechat" class="text-[42rpx] text-white" />
        </view>
        <text class="text-[32rpx] font-bold text-[#333]">微信授权测试</text>
        <text class="block text-[14rpx] text-[#666] mt-[10rpx]">测试微信授权登录功能</text>
      </view>
      
      <!-- 环境信息 -->
      <view class="bg-white rounded-[16rpx] p-[30rpx] mb-[30rpx] shadow-[0_2rpx_10rpx_rgba(0,0,0,0.05)]">
        <text class="text-[18rpx] font-medium text-[#333] mb-[20rpx] block">环境信息</text>
        <view class="space-y-[12rpx]">
          <view class="flex justify-between items-center">
            <text class="text-[14rpx] text-[#666]">运行环境:</text>
            <text class="text-[14rpx] text-[#333] font-medium">{{ systemInfo.platform }}</text>
          </view>
          <view class="flex justify-between items-center">
            <text class="text-[14rpx] text-[#666]">是否微信环境:</text>
            <text class="text-[14rpx]" :class="isWechatEnv ? 'text-[#07C160]' : 'text-[#FF4D4F]'">
              {{ isWechatEnv ? '是' : '否' }}
            </text>
          </view>
          <view class="flex justify-between items-center">
            <text class="text-[14rpx] text-[#666]">授权状态:</text>
            <text class="text-[14rpx]" :class="authStatus ? 'text-[#07C160]' : 'text-[#FF4D4F]'">
              {{ authStatus ? '已授权' : '未授权' }}
            </text>
          </view>
          <view class="flex justify-between items-center">
            <text class="text-[14rpx] text-[#666]">Token:</text>
            <text class="text-[14rpx] text-[#333] font-mono">{{ token || '无' }}</text>
          </view>
        </view>
      </view>
      
      <!-- 测试按钮 -->
      <view class="bg-white rounded-[16rpx] p-[30rpx] mb-[30rpx] shadow-[0_2rpx_10rpx_rgba(0,0,0,0.05)]">
        <text class="text-[18rpx] font-medium text-[#333] mb-[20rpx] block">测试操作</text>
        
        <view class="space-y-[20rpx]">
          <!-- 检查授权状态 -->
          <nut-button 
            type="primary" 
            size="large"
            class="w-full bg-[#2196F3] text-white border-none rounded-[12rpx] py-[16rpx] text-[16rpx] font-medium"
            @click="checkAuthStatus"
          >
            检查授权状态
          </nut-button>
          
          <!-- 开始授权 -->
          <nut-button 
            type="primary" 
            size="large"
            class="w-full bg-[#07C160] text-white border-none rounded-[12rpx] py-[16rpx] text-[16rpx] font-medium"
            :disabled="!isWechatEnv"
            @click="startAuth"
          >
            开始微信授权
          </nut-button>
          
          <!-- 清除授权 -->
          <nut-button 
            type="default" 
            size="large"
            class="w-full bg-white text-[#666] border border-[#ddd] rounded-[12rpx] py-[16rpx] text-[16rpx] font-medium"
            @click="clearAuth"
          >
            清除授权信息
          </nut-button>
          
          <!-- 跳转登录页 -->
          <nut-button 
            type="default" 
            size="large"
            class="w-full bg-white text-[#666] border border-[#ddd] rounded-[12rpx] py-[16rpx] text-[16rpx] font-medium"
            @click="goToLogin"
          >
            跳转登录页
          </nut-button>
        </view>
      </view>
      
      <!-- 日志信息 -->
      <view class="bg-white rounded-[16rpx] p-[30rpx] shadow-[0_2rpx_10rpx_rgba(0,0,0,0.05)]">
        <text class="text-[18rpx] font-medium text-[#333] mb-[20rpx] block">操作日志</text>
        <view class="bg-[#f8f9fa] rounded-[8rpx] p-[20rpx] max-h-[300rpx] overflow-y-auto">
          <view v-for="(log, index) in logs" :key="index" class="text-[12rpx] text-[#666] mb-[8rpx]">
            <text class="text-[#999]">[{{ log.time }}]</text>
            <text class="ml-[8rpx]" :class="log.type === 'error' ? 'text-[#FF4D4F]' : log.type === 'success' ? 'text-[#07C160]' : 'text-[#666]'">
              {{ log.message }}
            </text>
          </view>
          <view v-if="logs.length === 0" class="text-[12rpx] text-[#999] text-center py-[20rpx]">
            暂无日志
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Taro } from '@tarojs/taro'
import { Button as nutButton } from '@nutui/nutui-taro'
import { IconFont } from '@nutui/icons-vue-taro'
import { wechatAuth } from '@/core/config'

/**
 * 微信授权测试页面
 * @description 用于测试微信授权登录功能的完整流程
 */

// 系统信息
const systemInfo = ref<any>({})
const isWechatEnv = ref(false)
const authStatus = ref(false)
const token = ref('')
const logs = ref<Array<{time: string, message: string, type: 'info' | 'success' | 'error'}>>([])

/**
 * 添加日志
 * @param message 日志消息
 * @param type 日志类型
 */
const addLog = (message: string, type: 'info' | 'success' | 'error' = 'info') => {
  const time = new Date().toLocaleTimeString()
  logs.value.unshift({ time, message, type })
  
  // 限制日志数量
  if (logs.value.length > 50) {
    logs.value = logs.value.slice(0, 50)
  }
}

/**
 * 获取系统信息
 */
const getSystemInfo = () => {
  try {
    const info = Taro.getSystemInfoSync()
    systemInfo.value = info
    isWechatEnv.value = info.platform === 'wechat' || 
                       info.platform === 'weapp' ||
                       (typeof window !== 'undefined' && /MicroMessenger/i.test(navigator.userAgent))
    
    addLog(`系统信息获取成功: ${info.platform}`, 'success')
  } catch (error) {
    addLog(`获取系统信息失败: ${error}`, 'error')
  }
}

/**
 * 检查授权状态
 */
const checkAuthStatus = () => {
  try {
    const status = wechatAuth.checkAuthStatus()
    authStatus.value = status
    
    const storedToken = Taro.getStorageSync('token')
    token.value = storedToken || ''
    
    addLog(`授权状态检查: ${status ? '已授权' : '未授权'}`, status ? 'success' : 'info')
    
    if (status) {
      addLog(`Token: ${storedToken ? storedToken.substring(0, 20) + '...' : '无'}`, 'info')
    }
  } catch (error) {
    addLog(`检查授权状态失败: ${error}`, 'error')
  }
}

/**
 * 开始授权
 */
const startAuth = async () => {
  // try {
  //   addLog('开始微信授权流程...', 'info')
    
  //   if (!isWechatEnv.value) {
  //     addLog('当前环境不支持微信授权', 'error')
  //     Taro.showToast({
  //       title: '请在微信中打开',
  //       icon: 'none'
  //     })
  //     return
  //   }
    
  //   // 检查是否需要授权
  //   if (!wechatAuth.shouldAuth()) {
  //     addLog('无需重新授权', 'info')
  //     Taro.showToast({
  //       title: '无需重新授权',
  //       icon: 'none'
  //     })
  //     return
  //   }
    
  //   // 执行授权
  //   await wechatAuth.authorize()
  //   addLog('授权请求已发送', 'success')
    
  // } catch (error) {
  //   addLog(`授权失败: ${error}`, 'error')
  //   Taro.showToast({
  //     title: '授权失败',
  //     icon: 'none'
  //   })
  // }
}

/**
 * 清除授权信息
 */
const clearAuth = () => {
  try {
    Taro.removeStorageSync('token')
    Taro.removeStorageSync('tokenExpireTime')
    
    authStatus.value = false
    token.value = ''
    
    addLog('授权信息已清除', 'success')
    
    Taro.showToast({
      title: '授权信息已清除',
      icon: 'success'
    })
  } catch (error) {
    addLog(`清除授权信息失败: ${error}`, 'error')
  }
}

/**
 * 跳转登录页
 */
const goToLogin = () => {
  Taro.navigateTo({
    url: '/pages/webs/login'
  })
  addLog('跳转到登录页', 'info')
}

// 初始化
onMounted(() => {
  addLog('页面加载完成', 'info')
  getSystemInfo()
  checkAuthStatus()
})
</script> 